package org.spiderflow.permission.controller;

import org.spiderflow.common.redis.userinfo.RedisUserInfoUtil;
import org.spiderflow.config.ResponseResult;
import org.spiderflow.config.RestResultGenerator;
import org.spiderflow.config.permission.PermissionCheck;
import org.spiderflow.config.permission.PermissionCodeEnum;
import org.spiderflow.permission.entity.SysUserPermisson;
import org.spiderflow.permission.service.SysUserPermissionService;
import org.spiderflow.permission.service.impl.SysUserPermissionServiceImpl;
import org.spiderflow.permission.vo.AddPermissionRequest;
import org.spiderflow.users.entity.Users;
import org.spiderflow.users.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Nicky.Tang on 2020/5/7 9:58 PM
 *
 * @since 02.12.10
 */
@RestController
@RequestMapping("/permission")
@PermissionCheck(perCode = PermissionCodeEnum.quanxian)
public class PermissionController {
    @Autowired
    UsersService usersService;
    @Autowired
    SysUserPermissionService sysUserPermissionService;
    @Autowired
    RedisUserInfoUtil redisUserInfoUtil;

    @RequestMapping(value = "/getAllUserInfo")
    @ResponseBody

    public ResponseResult<List<Users>> getAllUserInfo(HttpServletRequest request) throws Exception {
        List<Users> usersList = usersService.findUserInfo(null);
        return RestResultGenerator.genResult(usersList, "查询用户权限信息成功！");
    }

    @RequestMapping(value = "/blockUp")
    @ResponseBody
    public ResponseResult<String> blockUp(HttpServletRequest request, @RequestBody Users users) throws Exception {
        usersService.blockUp(users);
        return RestResultGenerator.genResult("操作成功！");
    }

    @RequestMapping(value = "/addPermission")
    @ResponseBody
    public ResponseResult<String> blockUp(HttpServletRequest request, @RequestBody AddPermissionRequest userPers) throws Exception {
        sysUserPermissionService.removePermission(userPers);
        sysUserPermissionService.saveBatch(userPers.getPers());
        // 重置redis中用户的缓存信息
        List<Users> usersList = usersService.findUserInfo(userPers.getUserPhone());
        if(!CollectionUtils.isEmpty(usersList)){
            redisUserInfoUtil.initUserInfo(usersList.get(0));
        }
        return RestResultGenerator.genResult("赋权成功！");
    }

}
